<template>
  <div id="map" style="width: 100%;height: 100%;"/>
  <div id="search">
    <el-input v-model="shopName" style="width: 200px;margin-right: 10px;"/>
    <el-button type="primary" @click="doSearch">搜索</el-button>
    <el-button type="primary" @click="doRefresh">刷新</el-button>
    <div v-if="!isAll" style="max-height: 500px; overflow-y: scroll;">
      <el-card v-for="item in shops" :key="item.id" style="max-width: 480px">
        <div style="text-align: left;">
          <div>商户：{{ item.name }}</div>
          <div>电话：{{ item.phone }}</div>
          <div >地址：<el-button type="primary" link @click="showPosition(item)">{{ item.address }}</el-button> </div>
        </div>
      </el-card>
    </div>

  </div>

  <el-drawer v-model="dialogVisible" direction="rtl" title="商户信息">
    <el-form :model="editForm" label-position="right" label-width="auto">
      <el-form-item style="display: none;">
        <el-text class="mx-1">{{ editForm.id }}</el-text>
      </el-form-item>

      <el-form-item label="商户名">
        <el-text class="mx-1">{{ editForm.name }}</el-text>
      </el-form-item>

      <el-form-item label="经营者">
        <el-text class="mx-1">{{ editForm.owner }}</el-text>
      </el-form-item>

      <el-form-item label="联系方式">
        <el-text class="mx-1">{{ editForm.phone }}</el-text>
      </el-form-item>

      <el-form-item label="地址">
        <el-text class="mx-1">{{ editForm.address }}</el-text>
      </el-form-item>

      <el-form-item label="证件信息">
        <div>
          <el-image class="doc-images" fit="fill" :src="editForm.documentImage[0]"
                    :preview-src-list="[editForm.documentImage[0]]"/>
        </div>
        <div>
          <el-image class="doc-images" fit="fill" :src="editForm.documentImage[1]"
                    :preview-src-list="[editForm.documentImage[1]]"/>
        </div>
      </el-form-item>

      <el-form-item label="信用等级">
        <el-text class="mx-1">{{ editForm.level }}</el-text>
      </el-form-item>

      <el-form-item label="监管人员">
        <div>
          <el-image class="person-images" :src="editForm.checkPerson[0]"/>
        </div>
        <div>
          <el-image class="person-images" :src="editForm.checkPerson[1]"/>
        </div>
      </el-form-item>

      <el-form-item label="经度">
        <el-text class="mx-1">{{ editForm.position[0] }}</el-text>
      </el-form-item>

      <el-form-item label="维度">
        <el-text class="mx-1">{{ editForm.position[1] }}</el-text>
      </el-form-item>
    </el-form>
  </el-drawer>

</template>

<script setup>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import XYZ from 'ol/source/XYZ'
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import {Style, Fill, Stroke, Circle, Text} from 'ol/style';
import {fromLonLat} from 'ol/proj'
import {onMounted, ref} from 'vue';
import VectorSource from 'ol/source/Vector';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import Feature from 'ol/Feature';
import {Select} from "ol/interaction";

const shopName = ref('');
const appMap = ref({})
const shops = ref([]);
const isAll = ref(true);
const drawLayer = ref({});
const drawSource = ref(new VectorSource());
const drawStyles = [
  new Style({
    image: new Circle({
      radius: 5,
      fill: new Fill({color: 'red'}),
      stroke: new Stroke({color: 'black', width: 1}),
    }),
  }),
];

const mapUrl = ref(`tiles/{z}/{x}/{y}.png`)
// 创建选择器
const select = ref(new Select());

const dialogVisible = ref(false)

const editForm = ref({
  id: "",
  name: "",
  owner: "",
  phone: "",
  address: "",
  documentImage: ["", ""],
  level: "",
  checkPerson: [],
  position: ["", ""],
})

const init = () => {

  drawLayer.value = new VectorLayer({
    source: drawSource.value,
    style: drawStyles
  });

  appMap.value = new Map({
    layers: [
      new TileLayer({
        source: new XYZ({
          url: mapUrl.value
        })
      }),
      drawLayer.value
    ],
    view: new View({
      center: fromLonLat([118.886373, 39.432084]), // 地图中心点
      zoom: 15, // 初始缩放级别
      minZoom: 10, // 最小缩放级别
      maxZoom: 18 // 最大缩放级别
    }),
    target: 'map'
  });


  appMap.value.addInteraction(select.value);

// 监听选择事件
  select.value.on('select', function (event) {
    const fs = event.target.getFeatures().getArray();
    if (fs.length > 0) {
      editForm.value = fs[0].getProperties().shopInfo;
      dialogVisible.value = true;
    }
  });
}

function showPosition(item){
  let position = item.position;
  const center = fromLonLat([position[0], position[1]]);

  // 平滑地聚焦到新位置
  appMap.value.getView().animate({
    center: center,
    zoom: 18,
    duration: 1000 // 动画持续时间，单位毫秒
  })
}

async function loadAllData() {
  try {
    let fileContent = await window.api.readJsonFile("shop.json");
    let list = JSON.parse(fileContent);
    let listCount = list.length;
    if (typeof shopName.value !== "undefined" && shopName.value !== null && shopName.value !== '') {
      list = list.filter((item) => {
        return item.name.indexOf(shopName.value) !== -1
      });
    }
    shops.value = list;
    let shopsCount = list.length;
    if (listCount === shopsCount) {
      isAll.value = true;
    } else {
      isAll.value = false;
    }
    drawPoints();
    if(isAll.value === false && shops.value.length > 0) {
      showPosition(shops.value[0]);
    }
  } catch (e) {
    return [];
  }
}


function drawPoints() {

  for (let item of shops.value) {
    let feature = new Feature({
      geometry: new Point(fromLonLat([item.position[0], item.position[1]])),
    });
    feature.setProperties({
      shopInfo: item
    })
    feature.setStyle(new Style({
      image: new Circle({
        radius: 5,
        fill: new Fill({color: 'red'}),
        stroke: new Stroke({color: 'black', width: 1}),
      }),
      text: new Text({
        text: item.name,
        font: '12px Calibri, sans-serif',
        fill: new Fill({
          color: 'black',
        }),
        offsetX: 0,
        offsetY: -20,
      }),

    }));

    drawSource.value.addFeature(feature);
  }
}

function drawBorder() {

  let ps = [
    [118.867081, 39.442351],
    [118.867853, 39.432242],
    [118.883517, 39.420938],
    [118.886049, 39.417788],
    [118.904331, 39.419943],
    [118.908237, 39.423457],
    [118.908494, 39.426872],
    [118.896392, 39.439235],
    [118.892615, 39.443179],
    [118.867081, 39.442351],
  ].map(p => fromLonLat(p));

  let polygon = new Polygon([ps]);
  let feature = new Feature({geometry: polygon});
  let source = new VectorSource({features: [feature]});
  let vl = new VectorLayer({
    source: source,
    style: new Style({
      stroke: new Stroke({
        color: 'blue',
        width: 3
      })
    })
  });
  appMap.value.addLayer(vl);

}

function doSearch() {
  drawSource.value.clear();
  drawSource.value.refresh();
  loadAllData();
}

function doRefresh() {
  shopName.value = "";
  doSearch();
}

onMounted(() => {
  init()
  drawBorder();
  loadAllData();
});

</script>

<style scoped>
#map {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 900;
}

#search {
  text-align: center;
  z-index: 1000;
  position: absolute;
  top: 100px;
  left: 100px;
}

.doc-images {
  width: 400px;
  height: 300px;
}

.person-images {
  width: 200px;
  height: 200px;
}
</style>

